<?php
/**
 * Created by PhpStorm.
 * User: dale
 * Date: 2017/10/27
 * Time: 下午3:50
 */

namespace Admin\Mobile\Controllers;

//use Phalcon\Mvc\Dispatcher;
use Admin\Frontend\Controllers\DeviceController;
use Admin\Frontend\Controllers\TrackController;
use Admin\Models\device\XhsysUsertablet;
use Admin\Models\hrm\XhhrmDepart;
use Admin\Models\hrm\XhhrmStaff;
use Admin\Models\read\User;
use Admin\Models\school\XhschoolInfo;
use Admin\Models\sys\XhsysEnum;
use Admin\Models\device\XhsysAccountdevicelocked;
use Admin\Models\track\XhtrackTask;
use Admin\Models\user\XhsysUser;
use Admin\Models\XHsysDeviceStore;
use Couchbase\UserSettings;
use Helpers\Assets;
use Helpers\Device;
use Helpers\Hrm;
use Helpers\Main;
use Helpers\phpmailerException;
use Helpers\Tool;
use Helpers\UserPower;
use Helpers\XhException;
use Admin\Models\lm\XHLmCar;
use Admin\Models\lm\XHLmUseCar;
use Modules\Ims;
use Modules\Power;
use Phalcon\Exception;
use Phalcon\Mvc\Model\Query;
use Phalcon\Dispatcher;

class ShortcutController extends ControllerBase
{


//    public function beforeExecuteRoute(Dispatcher $dispatcher)
//    {
//        if (in_array(strtolower($dispatcher->getActionName()), [
//            strtolower('index'),
//            strtolower('getStaff'),
//        ])) {
//            return true;
//        }
//        if(!in_array($this->dispatcher->getActionName(), ['login','doLogin','checkNeedValid','checkVersion','registerQR','getAuthQR'])){
//            //检查是否已登陆，否则跳转到登陆页面
//            if (!\Helpers\User::isAdmin()) {
//                Main::goLoginPage();
//                return false;
//            }
//        }
//
//        return true;
//    }


    /**
     * 需求
     * created by dale 2017/10/26
     */
    public function needAction(){
        Assets::easyUIMobile();
        $this->view->pick('shortcut/track');
        Assets::importJs('js/myTool.js');
        Assets::importJs('js/mobilePage.js');
        Assets::importJs('js/shortcut/track.js');

        $this->view->setVars([
            'type'=>1,
        ]);
    }

    /**
     * bug
     * created by dale 2017/10/26
     */
    public function bugAction()
    {
        Assets::easyUIMobile();
        $this->view->pick('shortcut/track');
        Assets::importJs('js/myTool.js');
        Assets::importJs('js/mobilePage.js');
        Assets::importJs('js/shortcut/track.js');
        $this->view->setVars([
            'type'=>2,
        ]);
    }
    /**
     * 资源
     *
     * created by dale 20171026
     */
    public function resAction(){
        Assets::easyUIMobile();
        $this->view->pick('shortcut/track');
        Assets::importJs('js/myTool.js');
        Assets::importJs('js/mobilePage.js');
        Assets::importJs('js/shortcut/track.js');
        $this->view->setVars([
            'type'=>3,
        ]);
    }

    /**
     * 获取需求bug资源 分页   page rows
     *
     * @param $type
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by dale 20180242
     */
    public function getTrackTaskAction($type){
        $sql = "select iTTId,sTaskName,iState,tCreateDate from  XHTrack_Task  WHERE iTaskType = {$type} AND bDelete = 0  ";
        $data = Main::runSqlPage(['query' => " select :columns: from ({$sql}) as td ",'columns'=>'td.*']);
        $track = new TrackController();
        foreach ($data['rows'] as $index => $value){
            $data['rows'][$index]['iState'] = $track->getStateName($type,$value['iState']);
        }
        return $this->sendJsonResponse($data);
    }



    /**
     * 详情
     *
     * create by dale 20180131
     */
    public function taskDetailAction($iTTId){
        Assets::easyUIMobile();
        $this->view->pick('shortcut/taskDetail');
        Assets::importJs('js/myTool.js');
//        Assets::importJs('js/shortcut/taskDetail.js');
        $info = XhtrackTask::findFirst($iTTId)->toArray();
        if(isset($info['sSchoolId'])){
            $schoolIds = array_values(array_filter(explode(',',$info['sSchoolId'])));
            $schoolName = XhschoolInfo::getSchoolArray();
            foreach ($schoolIds as $index=>$id){
                $schoolIds[$index] = $schoolName[$id];
            }
            $info['sSchoolId'] = implode(',',$schoolIds);
        }
        if(isset($info['sOfferIds'])){
            $ids = array_values(array_filter(explode(',',$info['sOfferIds'])));
            $userName = XhsysUser::getUserNameById($ids);
            $info['sOfferIds'] = implode(',',$userName);
        }
        $this->view->setVars([
            'info'=>$info,
        ]);
    }


    /**
     * 获取模块数组
     *
     * @return string
     *
     * created by dale 20171129
     */
    public function getModuleAction(){

        $powerArr = [
            'data'=>[
//                0 =>['iconClass'=>'module-boxIn','module'=>'boxIn','name'=>'入库','power'=>false],
//                1 =>['iconClass'=>'module-boxOut','module'=>'boxOut','name'=>'出库','power'=>false],
                2 =>['iconClass'=>'module-reportDev','module'=>'reportDev','name'=>'上报','power'=>UserPower::checkUserPower('Ims_ReportDev')],
                3 =>['iconClass'=>'module-need','module'=>'need','name'=>'需求','power'=>UserPower::checkUserPower('Track_Demand')],
                4 =>['iconClass'=>'module-bug','module'=>'bug','name'=>'BUG','power'=>UserPower::checkUserPower('Track_BUG')],
                5 =>['iconClass'=>'module-res','module'=>'res','name'=>'资源','power'=>UserPower::checkUserPower('Track_Res')],
//                6 =>['iconClass'=>'module-unbind','module'=>'unbind','name'=>'解绑','power'=>false], //取消解绑功能
                7 =>['iconClass'=>'module-teacher','module'=>'teacher','name'=>'教师','power'=>UserPower::checkUserPower('School_List_Tch')],
                8 =>['iconClass'=>'module-student','module'=>'student','name'=>'学生','power'=>UserPower::checkUserPower('School_List_Stud')],
//                9 =>['iconClass'=>'module-count','module'=>'count','name'=>'统计','power'=>false],
//                10 =>['iconClass'=>'module-returnTablet','module'=>'returnTablet','name'=>'归还备用机','power'=>false],
//                11 =>['iconClass'=>'module-returnTablet','module'=>'returnDev','name'=>'设备归还','power'=>UserPower::checkUserPower('Device_registerList_Edit')],
//                12 =>['iconClass'=>'module-get' ,'module'=>'getTab','name'=>'设备领用','power'=>UserPower::checkUserPower('Device_registerList_Add')],
                13 =>['iconClass'=>'module-car' ,'module'=>'carList','name'=>'车辆','power'=>UserPower::checkUserPower('Lm_Car_CarList')],
                14 =>['iconClass'=>'module-car' ,'module'=>'carHistory','name'=>'用车记录','power'=>UserPower::checkUserPower('Lm_Car_CarList')],
//                14 =>['iconClass'=>'module-car' ,'module'=>'test','name'=>'测试','power'=>true],
                15 =>['iconClass'=>'module-get' ,'module'=>'registerQR','name'=>'应聘登记','power'=>true],
                ],
            'all'=>false,
        ];
        if(Main::getLoginUserInfo('logonName') == 'admin'){
            $powerArr['all']=true;
        }

        return json_encode($this->configArr($powerArr));

    }

    /**
     * 处理权限数组
     *
     * @param $powerArr  --原权限数组
     * @return array     --现数组
     *
     * created by dale 20171129
     * modified by dale 2017/12/8
     */
    private function configArr($powerArr){
        $configArr = [];
        if(!$powerArr['all']){
            foreach ($powerArr['data'] as $index=>$row){
                if($row['power']){
                    $configArr[] = $row;
                }
            }
        }else{
            $configArr = $powerArr['data'];
        }
//        return $configArr;
        return array_values($configArr);
    }

    /**
     * 解绑界面
     *
     * created by dale 20171123
     */
    public function unbindAction(){
        Assets::easyUIMobile();
        $this->view->pick('shortcut/unbind');
        Assets::importJs('js/myTool.js');
        Assets::importJs('js/shortcut/unbind.js');
    }

    /**
     * 保存解绑信息
     *
     * created by dale 2017/11/23
     */
    public function saveUnbindAction(){
        try{
            $code = $this->request->getPost('code','string');
            if(!$code){
                return $this->sendErrorResponse(500,'缺少设备码code');
            }
            $obj = XhsysAccountdevicelocked::findFirst([
                'conditions' => 'bDelete = 0 AND sDeviceNumber = :code:',
                'bind'      => ['code' =>$code ],
            ]);
            if($obj){
                $obj->bDelete = 1;
            }else{
                return $this->sendErrorResponse(500,'不存在该设备码');
            }

            if($obj->save()){
                return $this->sendSuccessResponse('解绑成功');
            }else{
                return $this->sendErrorResponse(500,'绑定失败');
            }
        }catch (\Exception $e){
            return  $this->sendErrorResponse(500,$e->getMessage());
        }
    }

    /**
     * 学校列表
     *
     * created by dale 20171124
     */
    public function schListAction(){
        Assets::easyUIMobile();
        $this->view->pick('shortcut/schList');
        Assets::importJs('js/myTool.js');
        Assets::importJs('js/shortcut/schList.js');
        $sql = 'select iSchoolId,sSchoolName from XHSchool_Info where bDelete = 0';
        $schoolIds = UserPower::getAuthorizationSchool(false);
        var_dump($schoolIds);
        $info = [];
        if ($schoolIds === false) {
            $info  = ['total'=>0,'rows'=>[]];
        }
        else if ($schoolIds !== true) {
            $sql .= ' AND iSchoolId IN (' . implode(',', $schoolIds) . ') ';
            $data = $this->db->query($sql)->fetchAll(\PDO::FETCH_ASSOC);
            $info = ['total'=>count($data),'rows'=>$data];
        }else {
            $data = $this->db->query($sql)->fetchAll(\PDO::FETCH_ASSOC);
            $info = ['total' => count($data), 'rows' => $data];
        }
        $this->view->setVars([
            'info' =>$info,
        ]);
    }

    /**
     * 学生教师列表
     *
     * created by dale 20171127
     */
    public function userListAction(){
        Assets::easyUIMobile();
        $this->view->pick('tp/listView');
        Assets::importJs('js/myTool.js');
        Assets::importJs('js/shortcut/userList.js');
    }

    /**
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * created by dale 20171127
     */
    public function getUserInfoAction(){
        $schoolId = $this->request->getPost('schoolId');
        $type = $this->request->getPost('type');
        $key  = $this->request->getPost('key');
        if(!$schoolId){
            return $this->sendErrorResponse(400,'缺少参数schoolId');
        }
        if(!$type){
            return $this->sendErrorResponse(400,'缺少参数type');
        }

//        $conditions = ' iSchoolId = :schoolId: AND iUserType =:type: AND bDelete = 0 AND bCompany = 0 AND bDisable = 0 AND bHistory = 0 ';
        $conditions = ' iSchoolId = :schoolId: AND iUserType =:type: AND bDelete = 0 AND bDisable = 0 AND bHistory = 0 ';
        $bind       = ['type'=>$type,'schoolId'=>$schoolId];

        if($key){
            $conditions .=' AND ( sLogonName like :key: OR sUserName like :key: )';
            $bind['key'] = '%'.$key.'%';
        }
        if($type ==4){
            $objs = XhsysUser::find([
                'columns'    => 'iUserId,sUserName,sLogonName',
                'conditions' => $conditions,
                'bind'       => $bind,
            ])->toArray();
        }else{
            $objs = XhsysUser::find([
                'columns'    => 'iUserId,sUserName,sAdClsName,sLogonName',
                'conditions' => $conditions,
                'bind'       => $bind,
                'order'      => 'sAdClsName desc',
            ])->toArray();
            $array = [];
            foreach($objs as $index => $obj){
                $array[$obj['sAdClsName']][] = $obj;
            }
            $objs =$array;
        }

        return $this->sendJsonResponse($objs);

    }

    /**
     * 用户功能界面网格状
     *
     * created by dale 20171127
     */
    public function userManageAction(){
        Assets::easyUIMobile();
        $this->view->pick('tp/gridView');
        Assets::importJs('js/myTool.js');
        Assets::importJs('js/shortcut/userManage.js');
    }

    /**
     * 获取用户功能信息
     *
     * @return string
     *
     * created by dale 20171127
     * modify by dale 20180528 添加学生端扫码登录
     */
    public function getUserManageAction(){
        $type   = $this->request->getPost('type');
        $userId = $this->request->getPost('userId');
        if($type ==1){  //学生
            $arr = [
                0 =>['iconClass'=>'module-resetPwd','module'=>'resetPwd','name'=>'重置密码','power'=>UserPower::checkUserPower('School_List_Stud_Pwd')],
                1 =>['iconClass'=>'module-useTablet','module'=>'useTablet','name'=>'使用备用机','power'=>UserPower::checkUserPower('School_List_Spare')],
                2 =>['iconClass'=>'module-returnTablet','module'=>'returnTablet','name'=>'归还备用机','power'=>true],
                3 =>['iconClass'=>'module-borrow','module'=>'borrow','name'=>'借用','power'=>UserPower::checkUserPower('School_List_Spare')],
                4 =>['iconClass'=>'module-returnBorrow','module'=>'returnBorrow','name'=>'归还借用','power'=>true],
                5 =>['iconClass'=>'module-scanLogin','module'=>'scanLogin','name'=>'扫码登录','power'=>UserPower::checkUserPower('School_List_Stud_Login')],
            ];

            $isUse = Device::hasSpare($userId);
            $isBorrow = Device::hasBorrow($userId);
            if(!$isUse && !$isBorrow){
                $arr[2]['power'] = false;
                $arr[4]['power'] = false;
            }else if ($isUse && !$isBorrow){ //已使用备用机
                $arr[1]['power'] = false;
                $arr[3]['power'] = false;
                $arr[4]['power'] = false;
            }else if (!$isUse && $isBorrow){
                $arr[1]['power'] = false;
                $arr[2]['power'] = false;
                $arr[3]['power'] = false;
            }
            $powerArr = [
                'data'=>$arr,
                'all'=>false,
            ];

        }else{ //老师
            $powerArr = [
                'data'=>[
                    0 =>['iconClass'=>'module-resetPwd','module'=>'resetPwd','name'=>'重置密码','power'=>UserPower::checkUserPower('School_List_Tch_Pwd')],
                    1 =>['iconClass'=>'module-useTablet','module'=>'useTablet','name'=>'使用备用机','power'=>UserPower::checkUserPower('School_List_Spare')],
                    2 =>['iconClass'=>'module-returnTablet','module'=>'returnTablet','name'=>'归还备用机','power'=>UserPower::checkUserPower('School_List_Spare')],
//                3 =>['iconClass'=>'module-unbind','module'=>'unbind','name'=>'解绑','power'=>false],
                ],
                'all'=>false,
            ];
        }

        if(Main::getLoginUserInfo('logonName') == 'admin'){
            $powerArr['all']=true;
        }
//        var_dump($powerArr);die();
        $powerArr = $this->configArr($powerArr);
        return json_encode($powerArr);
    }


    /**
     * 登录二维码
     *
     * create by xjq 20180529
     */
    public function scanLoginAction(){
        $this->view->pick('shortcut/scanLogin');
    }


    /**
     * 手机端注册码
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by dale  20181024
     */
    public function registerQRAction()
    {
        try {
            $this->view->pick('shortcut/registerQR');
            Assets::easyUIMobile();
            Assets::importJs('js/shortcut/registerQR.js');
            return $this->view->setVars([

            ]);
        } catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 获取认证信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181024
     */
    public function getAuthQRAction()
    {
        try {
            $endTime   = time() + 60; //14秒
            $token = "XhHrmRegister_{$endTime}";
            $token = urlencode($this->crypt->encryptBase64($token, 'xh_hrm'));
//            var_dump($token);
//            $token = $this->crypt->decryptBase64($token, 'xh_hrm');
//            var_dump($token);die;
            $baseUrl = Tool::getValue(Main::getConfigByName('hrm'), 'employUrl');
            if (!$baseUrl) {
                throw new XhException('配置项employUrl不存在');
            }
            $url =  $baseUrl .'hrm/resource/authCenter?token='.$token;
            return $this->response->setJsonContent(['code' =>  200, 'msg' => Tool::getQRBase64Uri($url)], JSON_UNESCAPED_UNICODE);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }


//    public function getTokenAction()
//    {
//        $endTime   = time() + 30; //14秒
//        $token = "XhHrmRegister_{$endTime}";
//        $token = urlencode($this->crypt->encryptBase64($token, 'xh_hrm'));
//        return $this->response->redirect('http://zjxhedu.xht.com/hrm/resource/index');
//    }

    /**
     * 重置密码
     *
     * created by dale 20171127
     */
    public function resetPwdAction(){
        Assets::easyUIMobile();
        $this->view->pick('shortcut/resetPwd');
        Assets::importJs('js/myTool.js');
        Assets::importJs('js/shortcut/resetPwd.js');
    }

    /**
     * 使用备用机
     *
     * created by dale 20171127
     */
    public function useTabletAction(){
        Assets::easyUIMobile();
        $this->view->pick('shortcut/useTablet');
        Assets::importJs('js/myTool.js');
        Assets::importJs('js/shortcut/useTablet.js');
    }

    /**
     * 使用备用机（ajax）  //去更新记录
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * created by dale 20171128
     */
    public function useTabDataAction(){
        $code       = $this->request->getPost('code');
        $userId     = $this->request->getPost('userId');
        if(!$code || !$userId ){
            return $this->sendErrorResponse(400, '缺少参数');
        }
        $devController = new DeviceController();
        try{
            $response = $devController->useSpareRegisterAction($code,$userId);
            return $response;
        }catch (\Exception $e){
            return $this->sendErrorResponse(500,$e->getMessage());
        }

    }

    /**
     * 归还备用机
     *
     * created by dale 20171127
     */
    public function returnTabletAction(){
        Assets::easyUIMobile();
        $this->view->pick('shortcut/returnTablet');
        Assets::importJs('js/myTool.js');
        Assets::importJs('js/shortcut/returnTablet.js');
    }

    /**
     * 归还设备
     *
     * created by dale 20171127
     */
    public function returnDevAction(){
        Assets::easyUIMobile();
        $this->view->pick('shortcut/returnTablet');
        Assets::importJs('js/myTool.js');
        Assets::importJs('js/shortcut/returnDev.js');
    }

    public function returnDevDataAction(){
        $code = $this->request->getPost('code','string');
        if(!$code){
            return $this->sendErrorResponse(400, '缺少参数设备码');
        }

        $obj = XhsysUsertablet::findFirst([
            'conditions' => 'bDelete = 0 AND sDevNumber = :sDevNumber: AND iReceiveStatus != 3',
            'bind'       => ['sDevNumber' => $code],
        ]);
        $dev = XhsysAccountdevicelocked::findFirst([
            'conditions' => 'sDeviceNumber =:sDeviceNumber: AND bDelete = 0',
            'bind'       => ['sDeviceNumber'=>$code]
        ]);

        if(!$obj && !$dev){
            return $this->sendErrorResponse(500,'找不到需要处理的设备');
        }

        $res = true;
        if($obj){
            $obj->bDone = 1;
            $obj->iReceiveStatus = 3;
            if(!$obj->save()){
                $res = false;
            }
        }

        if($dev){
            $dev->delete();
        }

        if($res){
            return $this->sendSuccessResponse('成功归还');
        }else{
            return $this->sendErrorResponse(500, '归还失败');
        }
    }

    /**
     * 归还备用机 （ajax）
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * created by dale 20171128
     */
    public function returnTabDataAction(){
        $code = $this->request->getPost('code');
        if(!$code){
           return $this->sendErrorResponse(400, '缺少参数设备码');
        }
        $obj = XhsysUsertablet::findFirst([
            'conditions' => 'bDelete = 0 AND sDevNumber = :sDevNumber: AND  iReceivePurpose = 1 AND bDone = 0',
            'bind'       => ['sDevNumber' => $code],
        ]);
        if(!$obj){
            return $this->sendErrorResponse(500, '未找到该备用机，请检查是否存在该设备码');
        }
        $obj->bDone = 1;
//        $obj->iReceiveStatus = 3;
        $res = $obj->save();
        if($res){
            return $this->sendSuccessResponse('成功返还');
        }else{
            return $this->sendErrorResponse(500, '返还失败');
        }
    }

    /**
     * 修改密码 (ajax)
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws \Exception
     *
     * created by dale 20171128
     * modified by dale 2017/12/8
     */
    public function savePasswordAction(){
        $userId  = $this->request->getPost('userId', 'int');
        if (!$userId){
            $userId = Main::getLoginUserInfo('userId');
        }
        $password = $this->request->getPost('password', 'string');
        if (!$userId || !$password) {
            return $this->sendErrorResponse(400, '参数不完整');
        }
        try{
            $res = \Helpers\User::setPassword($userId,$password);
            if($res){
                return $this->sendSuccessResponse('修改成功');
            }
        }catch (\Exception $e){
            return $this->sendErrorResponse(500,$e->getMessage());
        }
        return $this->sendSuccessResponse('修改成功');
    }

    /**
     * 领用机
     * @param int 1=>自用备用，2.教师3.学生。4老师
     * created by dale 2017127
     */
    public function getTabAction(){
        $this->view->pick('shortcut/getTab');
        Assets::easyUIMobile();
        Assets::select2();
        Assets::importJs('js/myTool.js');
        Assets::importJs('js/shortcut/getTab.js');
        $viewArr['type'] = [
            1 => '自用机',
            2 => '备用机',
            3 => '教师机',
            4 => '公用机'
        ];
        $this->view->setVars($viewArr);
    }

    /**
     * 学校教师接口
     *
     * @param $phoneNum
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * created by dale 2017128
     * modify by dale 20180319
     */
    public function getSchTchAction($phoneNum){
        $schoolId = $this->request->getQuery('schoolId');
        if(!$schoolId){
            if($phoneNum){
                $staff = XhhrmStaff::findFirst([
                    'columns'    => 'iUserId',
                    'conditions' => 'bDelete = 0 AND sSelfPhone = :phoneNum:  ',
                    'bind'       => ['phoneNum' => $phoneNum]
                ]);
                if($staff){
                    $schools =  \Helpers\User::getSchool(true,$staff->iUserId,false);
                }else{
                    $schools = \Helpers\User::getSchool(true,null,false);
                }
            }else{
                $schools = \Helpers\User::getSchool(true,null,false);
            }
            $arr = [];
            foreach ($schools as $index=>$value){
                $arr[] = ['iSchoolId'=>$index,'sSchoolName'=> $value];
            }
            return $this->sendJsonResponse($arr);
        }else{
            $teachers = XhsysUser::find([
                'columns'    => 'iUserId,sUserName',
//                'conditions' => 'bDelete=0 AND iSchoolId = :schoolId: AND iUserType = 4  and bCompany = 0 and bDisable = 0 and bHistory = 0',
                'conditions' => 'bDelete=0 AND iSchoolId = :schoolId: AND iUserType = 4 and bDisable = 0 and bHistory = 0',
                'bind'       => ['schoolId' => $schoolId, ]
            ]);
            $teachers  = $teachers->toArray();
            return $this->sendJsonResponse($teachers);
        }
    }

    private $registerEnum = [
        'iReceivePurpose'   => [0 => '自用', 1 => '备用', 2 => '学校公用', 3 => '教师机'],
        'iSource'           => [0 => '自动', 1 => '手动'],
        'bDone'             => [0 => '使用中', 1 => '使用完毕'],
    ];

    /**
     * 申请领用设备
     *
     * created by dale 2017128
     * modify by dale 20180814   设备领用入库
     */
    public function receiveNewTabletAction(){
        try {
            $type     = $this->request->getPost('type','int');
            $postData = $this->request->getPost();
            if(!$type){
                return $this->sendErrorResponse(400,'未选择领用设备类型');
            }
            $checkTab = XhsysUsertablet::findFirst([
                'conditions' => ' sDevNumber = :sDevNumber: ',
                'bind'       => ['sDevNumber' => $postData['code']],
                'order'      => 'iUTId desc'
            ]);
            if($checkTab  && !$checkTab->bDelete && $checkTab->iReceiveStatus  &&  $checkTab->iReceiveStatus != 3){
                return $this->sendErrorResponse(500,'设备未归还无法申请');
            }

            $tablet =new XhsysUsertablet();
            if ($type == 1 || $type == 2){
                if(!$postData['userName'] || !$postData['phoneNum'] || !$postData['code']){
                    return $this->sendErrorResponse(400,'缺少参数');
                }
                if($type == 2 && !$postData['schoolId']){
                    return $this->sendErrorResponse(400,'缺少参数');
                }
                $check = XhhrmStaff::findFirst([
                    'conditions' => 'sStaffName = :userName: AND sSelfPhone = :phoneNum: AND bDelete = 0',
                    'bind'       => ['userName' => $postData['userName'], 'phoneNum' => $postData['phoneNum']],
                ]);
                if(!$check){
                    return $this->sendErrorResponse(400,'找不到该职工账号');
                }
                if(!$check->iUserId){
                    return $this->sendErrorResponse(400,'该职工账号未绑定');
                }
                $user  = XhsysUser::findFirst($check->iUserId);
                if($type == 1){
                    $tablet->bDemo = $postData['bDemo'];
                }
                $tablet->sReceiverName    = $check->sStaffName;
                $tablet->sReceiverPhone   = $check->sSelfPhone;
                $tablet->sReceiverAccount = $user->sLogonName;
                $tablet->iReceivePurpose  = $type == 1 ? 0 : 1 ;
                if($tablet->iReceivePurpose == 1){
                    $tablet->iSchoolId    = $postData['schoolId'];
                    $tablet->bDone        = 1;
                }
                $tablet->iStaffId         = $check->iStaffId;

            }else if($type == 3){
                if(!$postData['schoolId'] || !$postData['userId']  || !$postData['code']){
                    return $this->sendErrorResponse(400,'缺少参数');
                }
                $user = XhsysUser::findFirst($postData['userId']);
                $tablet->sReceiverName    = $user->sUserName;
                $tablet->sReceiverPhone   = $user->sSelfPhone;
                $tablet->sReceiverAccount = $user->sLogonName;
                $tablet->iReceivePurpose  = 3; //教师机
                $tablet->iSchoolId        = $postData['schoolId'];

            }else if($type == 4){
                if(!$postData['schoolId'] ||!$postData['code']){
                    return $this->sendErrorResponse(400,'缺少参数');
                }
                $tablet->sReceiverName    = XhschoolInfo::findFirst($postData['schoolId'])->sSchoolName;
                $tablet->iReceivePurpose  = 2;
            }
            $tablet->sDevNumber   = $postData['code'];
            $tablet->tReceiveTime = date('Y-m-d H:i:s',time());
            if (!$tablet->save()) {
                return $this->sendErrorResponse(500, '失败');
            }
            return $this->sendSuccessResponse('成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e instanceof XhException ? $e->getDescription() : $e->getTrace());
        }
    }


//    public function testAction()
//    {
//        Assets::easyUIMobile();
//        $this->view->pick('shortcut/test');
//        Assets::importJs('js/myTool.js');
//        Assets::importJs('js/shortcut/test.js');
//    }

    public function borrowAction(){
        Assets::easyUIMobile();
        $this->view->pick('shortcut/borrow');
        Assets::importJs('js/myTool.js');
        Assets::importJs('js/shortcut/borrow.js');
    }


    public function returnBorrowAction(){
        $userId = $this->request->getPost('userId','int');
        if(!$userId){
            return $this->sendErrorResponse(400,'缺少参数');
        }
        $devLock = XhsysAccountdevicelocked::findFirst([
            'conditions' => 'bDelete = 0 AND iUserId = :userId:',
            'bind'       =>  ['userId' => $userId]
        ]);
        if(!$devLock){
            return $this->sendErrorResponse(400,'找不到借用设备');
        }
        $dev = new DeviceController();
        $repose = $dev->unbindBoundAction([$devLock->iADLId],2);
        return $repose;
    }

    /**
     * 确认用车
     *
     * create by dale 20180119
     */
    public function carListAction(){
        Assets::easyUIMobile();
        $this->view->pick('tp/listView');
        Assets::importJs('js/myTool.js');
        Assets::importJs('js/shortcut/carList.js');
    }

    /**
     * 获取车辆信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180119
     */
    public function getCarAction()
    {
        $showStatus = $this->request->getPost('showStatus', 'int');
        $sql = "select iUCId,iCarId,tStartTime,tRealStart,tRealEnd,tEndTime,iState  from  XHLm_UseCar WHERE iState = 3 AND tRealEnd is NULL  order by tStartTime ";
        $sql = "select c.* from ({$sql}) as c group by c.iCarId";
        $sql = "select c.iCarId,c.sCarName,c.sPlateNum,c.iPersonNum,c.bDelete,uc.iUCId,uc.tStartTime,uc.tRealStart,uc.tEndTime,uc.tRealEnd,uc.iState,c.iCreateUserId,c.tLastModifyDate,c.iLastModifyUserId from  XHLm_Car  as c 
                    LEFT JOIN ($sql) as uc ON uc.iCarId = c.iCarId WHERE c.bDelete = 0";

        $data = $this->db->fetchAll($sql);
        if (!$showStatus) {
            foreach ($data as $index=>$row){
                $data[$index]['useStatus'] = $row['tRealStart'] == null ? '未使用':'使用中';
            }
        }
        return $this->sendJsonResponse($data);
    }

    /**
     * 用车列表
     *
     * create by dale 20180120
     */
    public function useCarListAction(){
        Assets::easyUIMobile();
        $this->view->pick('shortcut/useCarList');
        Assets::importJs('js/myTool.js');
        Assets::importJs('js/shortcut/useCarList.js');

    }

    /**
     * 用车明细
     *
     * create by dale  20181113
     *
     * modify by dale 20181113
     */
    public function useCarAction(){
        $iUCId = $this->request->getQuery('iUCId','int');
        $isConfirm = $this->request->getQuery('confirm','int');
        Assets::easyUIMobile();
        $this->view->pick('shortcut/useCar');
        Assets::importJs('js/myTool.js');
        Assets::importJs('js/shortcut/useCar.js');

        $sql = "select *  from  XHLm_UseCar  WHERE iUCId = {$iUCId}";
        $data = $this->db->fetchOne($sql);
        if (Power::exist('Lm_Car_CarList_Confirm') && $data['tRealEnd'] == null && !$isConfirm) {
            $confirm = true;
        } else {
            $confirm = false;
        }
        $this->view->setVar('startUse', $data['tRealStart'] ? true :false );
        $data['sDpeName'] = XhhrmDepart::getDepEnum()[$data['iDepId']];

        $data['sTravellers'] = explode(',',$data['sTravellers']);
        $names = XhhrmStaff::getStaffNameById( $data['sTravellers']);
        $data['sTravellers'] = implode(',',$names);
        if($data['iCarId']!=null){
            $carSql = "select iCarId,sCarName,sPlateNum,iPersonNum from XHLm_Car  where iCarId = {$data['iCarId']}";
            $carInfo = $this->db->fetchOne($carSql);
            $data['sCarDesc'] = $carInfo['sCarName'].'('.$carInfo['sPlateNum'].')限载'.$carInfo['iPersonNum'].'人';
        }
        $this->view->setVars([
            'data'  => $data,
            'iUCId' => $iUCId,
            'showConfirm' => $confirm ,
            'cars' => $this->getCarEnum(),
            'staffArr' => Hrm::getInHireStaff()
        ]);
    }

    /**
     * 获取车辆信息
     *
     * @return array
     *
     * create by dale  20181113
     */
    private function getCarEnum()
    {
        $carSql = "select iCarId,sCarName,sPlateNum,iPersonNum from XHLm_Car  where bDelete = 0";
        $carInfo = $this->db->fetchAll($carSql);
        foreach ($carInfo as &$car ) {
            if ($car['sPlateNum']) {
                $car['sCarName'] = $car['sCarName'].'('.$car['sPlateNum'].')';
            }
        }
        return array_column($carInfo, 'sCarName', 'iCarId');
//        $data['sCarDesc'] = $carInfo['sCarName'].'('.$carInfo['sPlateNum'].')限载'.$carInfo['iPersonNum'].'人';
    }


    public function getUseCarAction($flag=false){
        try{
            $carId = $this->request->getPost('carId','int');

            $sql = "select iUCId,sApplyName,tStartTime,tEndTime,tRealStart,tRealEnd from XHLm_UseCar ";

            $conditionArr = [];
            if($carId){
                $conditionArr[]  = "iCarId = {$carId} ";
            }
            if($flag){ //历史
                $conditionArr[]  = " iState = 3 and tRealEnd is not null ";
            }else{  //当前
                $conditionArr[]  = " iState = 3 and tRealEnd is null ";
            }
            $sql .= ' where '.implode(' AND ',$conditionArr);

            $offset     = Main::getPageNumInfo('offset');
            $size       = Main::getPageNumInfo('rows');

            if($flag){
                $sql .= ' order by  tRealEnd desc ' ;
            }

            if ($size) {
                $sql .= " LIMIT {$offset},{$size}";
            }

            $data = $this->db->fetchAll($sql);

            return json_encode($data);
        }catch (\Exception $e){
            return $this->sendErrorResponse(500,$e->getMessage());
        }
    }

    /**
     * 根据电话获取姓名
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by dale 20180319
     */
    public function getNameByPhoneAction(){
        $phone = $this->request->getPost('phone');
        $staff = XhhrmStaff::findFirst([
            'columns'    => 'sStaffName',
            'conditions' => 'bDelete = 0 AND sSelfPhone = :sSelfPhone:',
            'bind'       => ['sSelfPhone' => $phone],
        ]);
        if(!$staff){
            return $this->sendErrorResponse(500,'没找到');
        }
        return $this->sendJsonResponse($staff->toArray());

    }

    /**
     * 用车记录
     *
     *
     * create by qgz 20190107
     */
    public function carHistoryAction()
    {
        Assets::easyUIMobile();
        $this->view->pick('tp/listView');
        Assets::importJs('js/myTool.js');
        Assets::importJs('js/shortcut/carHistory.js');
    }

    /**
     * 用车历史
     *
     *
     * create by qgz 20190107
     */
    public function useCarHistoryAction()
    {
        Assets::easyUIMobile();
        $this->view->pick('shortcut/useCarHistory');
        Assets::importJs('js/myTool.js');
        Assets::importJs('js/shortcut/useCarHistory.js');

    }

    /**
     * 获取用车历史数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
     *
     * create by qgz 20190107
     */
    public function getUseCarHistoryAction()
    {
        try {
            $carId = $this->request->getPost('carId', 'int');
            $sql = "select iUCId,sApplyName,tStartTime,tEndTime,tRealStart,tRealEnd,iState from XHLm_UseCar ";
            $conditionArr = [];
            if ($carId) {
                $conditionArr[] = " iCarId = {$carId} ";
            }
            $conditionArr[] = " iState != 4 and tRealEnd is null ";
            $sql .= ' where ' . implode(' AND ', $conditionArr) . ' order by  tEndTime desc ';
            $data = $this->db->fetchAll($sql);
            return json_encode($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

}